{ "cells": [ { "cell_type": "markdown", "metadata": { "school_cell_uuid": "c190ff5d2f374355986c7ca85d29bf70" }, "source": [ "# 4.2 데이터 입출력" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "6d216f42f1fd4aec87b08532409ba26c" }, "source": [ "Pandas는 데이터 파일을 읽어 데이터프레임을 만들 수 있다. 다음처럼 여러가지 포맷을 지원한다.\n", "\n", "* CSV\n", "* Excel\n", "* HTML\n", "* JSON\n", "* HDF5\n", "* SAS\n", "* STATA\n", "* SQL" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "f0db807a271f4add8e82f69d883dbb87" }, "source": [ "여기에서는 가장 단순하지만 널리 사용되는 CSV(Comman Separated Value) 포맷 입출력에 대해 살펴본다. CSV 파일 포맷은 데이터 값이 쉽표(comma)로 구분되는 텍스트 파일이다. " ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "4223190dec34477986120b1ff8a403d0" }, "source": [ "## `%%writefile` 명령" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "471c1baaa51f40ae93aef6c558935c8f" }, "source": [ "샘플 데이터로 사용할 CSV 파일을 `%%writefile` 매직(magic) 명령으로 만들어보자. 이 명령은 셀에 서술한 내용대로 텍스트 파일을 만드는 명령이다." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "school_cell_uuid": "b01980126899432f820eb27f17152aa8", "tags": [ "remove-cell" ] }, "outputs": [], "source": [ "!rm -rf sample?.*" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "school_cell_uuid": "04b3ff9d1cae45dd8beaf4c7e641ba8a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing sample1.csv\n" ] } ], "source": [ "%%writefile sample1.csv\n", "c1, c2, c3\n", "1, 1.11, one\n", "2, 2.22, two\n", "3, 3.33, three" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "585cf606dbaf46a69ca3c2150d04c165" }, "source": [ "## CSV 파일 입력" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "6373d2d133e74d59a6ff710d20233f74" }, "source": [ "CSV 파일로부터 데이터를 읽어 데이터프레임을 만들 때는 `pandas.read_csv` 함수를 사용한다. 함수의 입력값으로 파일 이름을 넣는다." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "school_cell_uuid": "a11e9a06250a48ccb58a55f92a42f790" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
c1c2c3
011.11one
122.22two
233.33three
\n", "
" ], "text/plain": [ " c1 c2 c3\n", "0 1 1.11 one\n", "1 2 2.22 two\n", "2 3 3.33 three" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pd.read_csv('sample1.csv')" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "9f7563f5d3844ebf98960a09a26bf054" }, "source": [ "위에서 읽은 데이터에는 열 인덱스는 있지만 행 인덱스 정보가 없으므로 0부터 시작하는 정수 인덱스가 자동으로 추가되었다. \n", "\n", "만약 데이터 파일에 열 인덱스 정보가 없는 경우에는 `read_csv` 명령의 `names` 인수로 설정할 수 있다." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "school_cell_uuid": "c82a70ae7c4e48178dedda62df3c9cb9" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing sample2.csv\n" ] } ], "source": [ "%%writefile sample2.csv\n", "1, 1.11, one\n", "2, 2.22, two\n", "3, 3.33, three" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "school_cell_uuid": "330426027afe4a4fbd8fb68c34602a1f" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
c1c2c3
011.11one
122.22two
233.33three
\n", "
" ], "text/plain": [ " c1 c2 c3\n", "0 1 1.11 one\n", "1 2 2.22 two\n", "2 3 3.33 three" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pd.read_csv('sample2.csv', names=['c1', 'c2', 'c3'])" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "ae8f956f97c74e4f921f174ee52dda55" }, "source": [ "만약 테이블 내의 특정한 열을 행 인덱스로 지정하고 싶으면 `index_col` 인수를 사용한다." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "school_cell_uuid": "a6674bc479594bf08fd3f977dae3ca0e" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
c2c3
c1
11.11one
22.22two
33.33three
\n", "
" ], "text/plain": [ " c2 c3\n", "c1 \n", "1 1.11 one\n", "2 2.22 two\n", "3 3.33 three" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pd.read_csv('sample1.csv', index_col='c1')" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "c7d03aa1fdcd49c69ae3ad4981dd82fa" }, "source": [ "확장자가 CSV가 아닌 파일 즉, 데이터를 구분하는 구분자(separator)가 쉼표(comma)가 아니면 `sep` 인수를 써서 구분자를 사용자가 지정해준다. 만약 길이가 정해지지 않은 공백이 구분자인 경우에는 `\\s+` 정규식(regular expression) 문자열을 사용한다." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "school_cell_uuid": "ce5e05c5b3b34eeb85d8e84f5b65f921" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing sample3.txt\n" ] } ], "source": [ "%%writefile sample3.txt\n", "c1 c2 c3 c4\n", "0.179181 -1.538472 1.347553 0.43381\n", "1.024209 0.087307 -1.281997 0.49265\n", "0.417899 -2.002308 0.255245 -1.10515" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "school_cell_uuid": "19bce18706a249b8b9f8ec5d1a15a4d2" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
c1c2c3c4
00.179181-1.5384721.3475530.43381
11.0242090.087307-1.2819970.49265
20.417899-2.0023080.255245-1.10515
\n", "
" ], "text/plain": [ " c1 c2 c3 c4\n", "0 0.179181 -1.538472 1.347553 0.43381\n", "1 1.024209 0.087307 -1.281997 0.49265\n", "2 0.417899 -2.002308 0.255245 -1.10515" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pd.read_table('sample3.txt', sep='\\s+')" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "716de67f99fa4073b8c641f6caae9d43" }, "source": [ "만약 자료 파일 중에 건너 뛰어야 할 행이 있으면 `skiprows` 인수를 사용한다." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "school_cell_uuid": "afd1d8541cdf46e590abb486d3226817" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing sample4.txt\n" ] } ], "source": [ "%%writefile sample4.txt\n", "파일 제목: sample4.txt\n", "데이터 포맷의 설명:\n", "c1, c2, c3\n", "1, 1.11, one\n", "2, 2.22, two\n", "3, 3.33, three" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "school_cell_uuid": "ab27874de370404e9e290a0f1e57a974" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
c1c2c3
011.11one
122.22two
233.33three
\n", "
" ], "text/plain": [ " c1 c2 c3\n", "0 1 1.11 one\n", "1 2 2.22 two\n", "2 3 3.33 three" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pd.read_csv('sample4.txt', skiprows=[0, 1])" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "a96dbf68be95433ea16e2493d4905329" }, "source": [ "특정한 값을 NaN으로 취급하고 싶으면 `na_values` 인수에 NaN 값으로 취급할 값을 넣는다." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "school_cell_uuid": "ad0bac04eec146e7b4fc7b69f3fba231" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing sample5.csv\n" ] } ], "source": [ "%%writefile sample5.csv\n", "c1, c2, c3\n", "1, 1.11, one\n", "2, , two\n", "누락, 3.33, three" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "school_cell_uuid": "954ab32395244769bf464831e0476097" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
c1c2c3
01.01.11one
12.0two
2NaN3.33three
\n", "
" ], "text/plain": [ " c1 c2 c3\n", "0 1.0 1.11 one\n", "1 2.0 two\n", "2 NaN 3.33 three" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = pd.read_csv('sample5.csv', na_values=['누락'])\n", "df" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "e8d7e3be4edd44abb969b861b6a3118e" }, "source": [ "## CSV 파일 출력" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "7320d2780f224e4ba05ee485ac7c615e" }, "source": [ "지금까지와 반대로 파이썬의 데이터프레임 값을 CSV 파일로 출력하고 싶으면 `to_csv` 메서드를 사용한다." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "school_cell_uuid": "99ee0967ffc2407b82364fc6618976da" }, "outputs": [], "source": [ "df.to_csv('sample6.csv')" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "ceb06c9898434a8a9f331f45c3461640" }, "source": [ "리눅스나 맥에서는 `cat` 셸 명령으로 파일의 내용을 확인할 수 있다. 윈도우에서는 `type` 함수를 사용한다. 느낌표(!)는 셸 함수를 사용하기 위한 아이파이썬(IPython) 매직 명령이다." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "school_cell_uuid": "82fe9c3d96954f25beeaa9ad7c28835d" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ",c1, c2, c3\n", "0,1.0, 1.11, one\n", "1,2.0, , two\n", "2,, 3.33, three\n" ] } ], "source": [ "!cat sample6.csv # 윈도우에서는 !type sample6.csv 함수를 사용" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "23e7679e86a34fca9abe6da6aa74bb68" }, "source": [ "파일을 읽을 때와 마찬가지로 출력할 때도 `sep` 인수로 구분자를 바꿀 수 있다." ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "school_cell_uuid": "94886907e74046f496adb3a1124d0b41" }, "outputs": [], "source": [ "df.to_csv('sample7.txt', sep='|')" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "school_cell_uuid": "19776531502b415a90a6493d8ab4325c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "|c1| c2| c3\n", "0|1.0| 1.11| one\n", "1|2.0| | two\n", "2|| 3.33| three\n" ] } ], "source": [ "!cat sample7.txt" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "8ed023c1b13c42fab7638a5fd6e184a0" }, "source": [ "또 `na_rep` 인수로 NaN 표시값을 바꿀 수도 있다." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "school_cell_uuid": "88a5884762074c9eb8d31c2315dabf43" }, "outputs": [], "source": [ "df.to_csv('sample8.csv', na_rep='누락')" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "school_cell_uuid": "dfdc80cbf1d74d8ca416f02ce380bd9c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ",c1, c2, c3\n", "0,1.0, 1.11, one\n", "1,2.0, , two\n", "2,누락, 3.33, three\n" ] } ], "source": [ "!cat sample8.csv" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "febf13e8c64747e0b2304d336df52625" }, "source": [ "`index`, `header` 인수를 지정하여 인덱스 및 헤더 출력 여부를 지정하는 것도 가능하다." ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "school_cell_uuid": "9426f4474213449eb4b4afae3b7e34cc" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
c1c2c3
a1.01.11one
b2.0two
cNaN3.33three
\n", "
" ], "text/plain": [ " c1 c2 c3\n", "a 1.0 1.11 one\n", "b 2.0 two\n", "c NaN 3.33 three" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.index = [\"a\", \"b\", \"c\"]\n", "df" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "school_cell_uuid": "17fd313193c546b68518dacc4e81089e" }, "outputs": [], "source": [ "df.to_csv('sample9.csv', index=False, header=False)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "school_cell_uuid": "b5cc2ffbc57f42c5b3729bb4883ce23c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.0, 1.11, one\n", "2.0, , two\n", ", 3.33, three\n" ] } ], "source": [ "!cat sample9.csv # 윈도우에서는 !type sample6.csv 함수를 사용" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "9445a995ccc648b99f5aff1fb7f3db82" }, "source": [ "## 인터넷 상의 CSV 파일 입력" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "5fc91f8e7370410492fd727deba9ed2b" }, "source": [ "웹상에는 다양한 데이터 파일이 CSV 파일 형태로 제공된다. `read_csv` 명령 사용시 파일 패스 대신 URL을 지정하면 Pandas가 직접 해당 파일을 다운로드하여 읽어들인다. 다음은 저자의 github 웹사이트에 저장되어 있는 데이터 파일을 원격으로 읽는 명령이다." ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "school_cell_uuid": "d74b6350c95c40839b7c4d53a0b9450d" }, "outputs": [], "source": [ "df = pd.read_csv(\"https://raw.githubusercontent.com/datascienceschool/docker_rpython/master/data/titanic.csv\")" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "8d7dd1e60d504ea6afbaee0d61ac73ed" }, "source": [ "이 데이터프레임은 실제로 데이터 갯수, 즉 행(row)의 수가 890개가 넘는 대량의 데이터이다. 이렇게 데이터의 수가 많을 경우, 데이터프레임의 표현(representation)은 데이터 앞, 뒤의 일부분만 보여준다. 보여줄 행의 수는 `display.max_rows` 옵션으로 정할 수 있다." ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "school_cell_uuid": "8d26823cb1744c548cd40ac8cfbb43ce" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS
3411Futrelle, Mrs. Jacques Heath (Lily May Peel)female35.01011380353.1000C123S
4503Allen, Mr. William Henrymale35.0003734508.0500NaNS
.......................................
88688702Montvila, Rev. Juozasmale27.00021153613.0000NaNS
88788811Graham, Miss. Margaret Edithfemale19.00011205330.0000B42S
88888903Johnston, Miss. Catherine Helen \"Carrie\"femaleNaN12W./C. 660723.4500NaNS
88989011Behr, Mr. Karl Howellmale26.00011136930.0000C148C
89089103Dooley, Mr. Patrickmale32.0003703767.7500NaNQ
\n", "

891 rows × 12 columns

\n", "
" ], "text/plain": [ " PassengerId Survived Pclass \\\n", "0 1 0 3 \n", "1 2 1 1 \n", "2 3 1 3 \n", "3 4 1 1 \n", "4 5 0 3 \n", ".. ... ... ... \n", "886 887 0 2 \n", "887 888 1 1 \n", "888 889 0 3 \n", "889 890 1 1 \n", "890 891 0 3 \n", "\n", " Name Sex Age SibSp \\\n", "0 Braund, Mr. Owen Harris male 22.0 1 \n", "1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 \n", "2 Heikkinen, Miss. Laina female 26.0 0 \n", "3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 \n", "4 Allen, Mr. William Henry male 35.0 0 \n", ".. ... ... ... ... \n", "886 Montvila, Rev. Juozas male 27.0 0 \n", "887 Graham, Miss. Margaret Edith female 19.0 0 \n", "888 Johnston, Miss. Catherine Helen \"Carrie\" female NaN 1 \n", "889 Behr, Mr. Karl Howell male 26.0 0 \n", "890 Dooley, Mr. Patrick male 32.0 0 \n", "\n", " Parch Ticket Fare Cabin Embarked \n", "0 0 A/5 21171 7.2500 NaN S \n", "1 0 PC 17599 71.2833 C85 C \n", "2 0 STON/O2. 3101282 7.9250 NaN S \n", "3 0 113803 53.1000 C123 S \n", "4 0 373450 8.0500 NaN S \n", ".. ... ... ... ... ... \n", "886 0 211536 13.0000 NaN S \n", "887 0 112053 30.0000 B42 S \n", "888 2 W./C. 6607 23.4500 NaN S \n", "889 0 111369 30.0000 C148 C \n", "890 0 370376 7.7500 NaN Q \n", "\n", "[891 rows x 12 columns]" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pd.set_option(\"display.max_rows\", 20) # 앞뒤로 모두 20행만 보여준다.\n", "df" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "f5aa795ed0c04da0bedbc0cb87e679cc" }, "source": [ "만약 앞이나 뒤의 특정 갯수만 보고 싶다면 `head` 메서드나 `tail` 메서드를 이용한다. 메서드 인수로 출력할 행의 수를 넣을 수도 있다." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "school_cell_uuid": "39378b2bd2f5423bac03a73fff37b009" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS
3411Futrelle, Mrs. Jacques Heath (Lily May Peel)female35.01011380353.1000C123S
4503Allen, Mr. William Henrymale35.0003734508.0500NaNS
\n", "
" ], "text/plain": [ " PassengerId Survived Pclass \\\n", "0 1 0 3 \n", "1 2 1 1 \n", "2 3 1 3 \n", "3 4 1 1 \n", "4 5 0 3 \n", "\n", " Name Sex Age SibSp \\\n", "0 Braund, Mr. Owen Harris male 22.0 1 \n", "1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 \n", "2 Heikkinen, Miss. Laina female 26.0 0 \n", "3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 \n", "4 Allen, Mr. William Henry male 35.0 0 \n", "\n", " Parch Ticket Fare Cabin Embarked \n", "0 0 A/5 21171 7.2500 NaN S \n", "1 0 PC 17599 71.2833 C85 C \n", "2 0 STON/O2. 3101282 7.9250 NaN S \n", "3 0 113803 53.1000 C123 S \n", "4 0 373450 8.0500 NaN S " ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.head()" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "school_cell_uuid": "24ed98afaf4c447e9795b01ac576617e" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
88989011Behr, Mr. Karl Howellmale26.00011136930.00C148C
89089103Dooley, Mr. Patrickmale32.0003703767.75NaNQ
\n", "
" ], "text/plain": [ " PassengerId Survived Pclass Name Sex Age SibSp \\\n", "889 890 1 1 Behr, Mr. Karl Howell male 26.0 0 \n", "890 891 0 3 Dooley, Mr. Patrick male 32.0 0 \n", "\n", " Parch Ticket Fare Cabin Embarked \n", "889 0 111369 30.00 C148 C \n", "890 0 370376 7.75 NaN Q " ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.tail(2)" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "a21a5a4a4b4c45819db7f0cb456557e9" }, "source": [ "## 인터넷 상의 데이터 베이스 자료 입력" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "996c3f2ffaa34d6b981bf6388c0256b0" }, "source": [ "pandas_datareader 패키지의 `DataReader` 을 사용하면 일부 인터넷 사이트의 자료를 바로 pandas로 읽어들일 수 있다. pandas_datareader 패키지는 판다스와 별도로 설치해야 한다. 다음은 pandas_datareader 패키지가 제공하는 인터넷 사이트의 예이다. 일부 인터넷 사이트는 유료이므로 별도의 가입절차를 거쳐야 한다.\n", "\n", "* FRED\n", "* Fama/French\n", "* World Bank\n", "* OECD\n", "* Eurostat\n", "* EDGAR Index\n", "* TSP Fund Data\n", "* Oanda currency historical rate\n", "* Nasdaq Trader Symbol Definitions\n", "\n", "자세한 내용은 다음 웹사이트를 참조한다.\n", "* https://pandas-datareader.readthedocs.io/en/latest/index.html\n" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "f05a8380f73049e7a2c2c94ebaa8c0f3" }, "source": [ "날짜는 datetime 패키지를 사용하여 지정해도 되고 문자열을 바로 사용해도 된다. (이때는 내부적으로 dateutil 패키지를 사용한다." ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "school_cell_uuid": "07f4fa9a4ba048399d05d9bb0bb4bd44" }, "outputs": [], "source": [ "import datetime\n", "dt_start = datetime.datetime(2015, 1, 1)\n", "dt_end = \"2016, 6, 30\"" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "5d82d45c9c474c92bda7d5d71f64471d" }, "source": [ "`data_source` 인수로 데이터를 읽어올 웹 사이트를 지정한다. 데이터의 코드는 웹 사이트에서 검색하여 알아내야 한다. 다음은 FRED 데이터베이스에서 미국 국가총생산(GDP), 모든 항목을 포함한 소비자 가격 지수(CPIAUCSL), 식료품 및 연로를 제외한 소비자 가격 지수(CPILFESL)를 가져오는 예이다. 웹사이트에서 자세한 데이터에 대한 세부적인 사항이나 값을 확인할 수 있다.\n", "\n", "* https://fred.stlouisfed.org/series/GDP\n", "* https://fred.stlouisfed.org/series/CPIAUCSL\n", "* https://fred.stlouisfed.org/series/CPILFESL" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "school_cell_uuid": "c5ef2de584dc41e98704859e8e3194e2" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
GDP
DATE
2015-04-0118223.577
2015-07-0118347.425
2015-10-0118378.803
2016-01-0118470.156
2016-04-0118656.207
\n", "
" ], "text/plain": [ " GDP\n", "DATE \n", "2015-04-01 18223.577\n", "2015-07-01 18347.425\n", "2015-10-01 18378.803\n", "2016-01-01 18470.156\n", "2016-04-01 18656.207" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas_datareader as pdr\n", "\n", "gdp = pdr.get_data_fred('GDP', dt_start, dt_end)\n", "gdp.tail()" ] }, { "cell_type": "markdown", "metadata": { "school_cell_uuid": "f35644fca6884832b4e9601955adef36" }, "source": [ "데이터 코드에 리스트를 넣으면 여러개의 데이터를 동시에 가져온다." ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "school_cell_uuid": "e0da3bedad84419f89570d829703289c" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
CPIAUCSLCPILFESL
DATE
2016-02-01237.514245.644
2016-03-01237.990245.964
2016-04-01238.835246.467
2016-05-01239.440247.036
2016-06-01240.144247.435
\n", "
" ], "text/plain": [ " CPIAUCSL CPILFESL\n", "DATE \n", "2016-02-01 237.514 245.644\n", "2016-03-01 237.990 245.964\n", "2016-04-01 238.835 246.467\n", "2016-05-01 239.440 247.036\n", "2016-06-01 240.144 247.435" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "inflation = pdr.get_data_fred([\"CPIAUCSL\", \"CPILFESL\"], dt_start, dt_end)\n", "inflation.tail()" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "tags": [ "remove-cell" ] }, "outputs": [], "source": [ "!rm -rf sample?.*" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "celltoolbar": "Edit Metadata", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false } }, "nbformat": 4, "nbformat_minor": 4 }